<?php

namespace model;

class Stats {

    private $queries;
    private $names;

    public function __construct() {
        $this->queries[1] = "select day(`OrderDate`) as `date`, sum(`TotalCost`) as `count`,`ShopID`, `OrderDate` from `tblorder` group by `date` having month(`OrderDate`)=:month and year(`OrderDate`)=:year and `ShopID`=:shop";
        $this->queries[] = "SELECT day(`LoginDate`) as `date`, count(`PersonID`) as `count`,`ShopID`,`LoginDate` FROM `tblloglogin` group by day(`LoginDate`) having month(`LoginDate`)=:month and year(`LoginDate`)=:year and ShopID=:shop";
        $this->queries[] = "select day(`OrderDate`) as `date`, count(`tblproductorder`.`Amount`) as `count`,`ShopID`, `OrderDate` from `tblorder` inner join `tblproductorder` on `tblproductorder`.`OrderID`=`tblorder`.`OrderID` group by `date` having month(`OrderDate`)=:month and year(`OrderDate`)=:year and `ShopID`=:shop";
        $this->queries[] = "select day(`OrderDate`) as `date`, count(`OrderID`) as `count`,`ShopID`, `OrderDate` from `tblorder` group by `date` having month(`OrderDate`)=:month and year(`OrderDate`)=:year and `ShopID`=:shop";
        $this->queries[] = "select day(`RegisterDate`) as `date`, count(`tblcustomer`.`PersonID`) as `count`,`ShopID`,`RegisterDate` from `tblcustomer` inner join `tblperson` on `tblcustomer`.`PersonID`=`tblperson`.`PersonID` group by `date` having month(`RegisterDate`)=:month and year(`RegisterDate`)=:year and `ShopID`=:shop";

        $this->names[1] = "Wartość zamówień";
        $this->names[] = "Ilość logowań";
        $this->names[] = "Liczba kupionych produktów";
        $this->names[] = "Liczba zamówień";
        $this->names[] = "Liczba zarejestrowanych klientów";
    }

    public function getStats($year, $month, $ShopID, $statsID) {
        $database = \library\Registry::get("database")->initialize()->connect();
        $stmt = $database->prepare($this->queries[$statsID]);
        $date = new \model\Date($year);
        $stmt->execute([":month" => $month, ":year" => $year, ":shop" => $ShopID]);
        $array = $stmt->fetchAll(\PDO::FETCH_OBJ | \PDO::FETCH_GROUP);
        $stats = array();
        $monthObj = $date->getMonth($month);
        $max = 0;
        for ($i = 1; $i < $monthObj->days; $i++) {
            if (isset($array[$i])) {
                if ($max < $array[$i][0]->count) {
                    $max = $array[$i][0]->count;
                }
                $stats[$i] = $array[$i][0]->count;
            } else {
                $stats[$i] = 0;
            }
        }
        return ["name" => $this->names[$statsID], "stats" => $stats, "max" => $max];
    }
    public function getNames(){
        return $this->names;
    }
}
